﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;

namespace HR.Areas.letao.Controllers
{
    public class UpdateController : ApiController
    {
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns>成功返回图片URL，失败则返回错误信息</returns>
        [HttpPost]
        public object UpLoad()
        {
            try
            {
                var content = Request.Content;
                var tempUploadFiles = "/UpLoad/Images/";
                var newFileName = "";
                string filePath = "";
                string extname = "";
                string returnurl = "";
                var sp = new MultipartMemoryStreamProvider();
                Task.Run(async () => await Request.Content.ReadAsMultipartAsync(sp)).Wait();
                foreach (var item in sp.Contents)
                {
                    if (item.Headers.ContentDisposition.FileName != null)
                    {
                        var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                        FileInfo file = new FileInfo(filename);
                        string fileTypes = "gif,jpg,jpeg,png,bmp";
                        if (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) == -1)
                        {
                            throw new ApplicationException("不支持上传文件类型");
                        }
                        //if (file.Length> 5242880)
                        //{
                        //    throw new UserFriendlyException(L("文件过大"));
                        //}
                        extname = filename.Substring(filename.LastIndexOf('.'), (filename.Length - filename.LastIndexOf('.')));
                        newFileName = Guid.NewGuid().ToString().Substring(0, 6) + extname;


                        //string newFilePath = DateTime.Now.ToString("yyyy-MM-dd") + "/";
                        string newFilePath = DateTime.Now.ToString("yyyyMMdd") + "/";//格式化一下
                        if (!Directory.Exists(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath))
                        {
                            Directory.CreateDirectory(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath);
                        }
                        filePath = Path.Combine(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath, newFileName);
                        returnurl = Path.Combine(tempUploadFiles + newFilePath, newFileName);
                        var ms = item.ReadAsStreamAsync().Result;
                        using (var br = new BinaryReader(ms))
                        {
                            if (ms.Length > 1048576 * 5)
                            {
                                //throw new UserFriendlyException(L("文件过大"));
                            }
                            var data = br.ReadBytes((int)ms.Length);
                            File.WriteAllBytes(filePath, data);
                        }
                    }
                }
                // return returnurl;
                //return new BaseResponse<string> { Success = true, Data = returnurl };
                Dictionary<string, object> dt = new Dictionary<string, object>()
                {
                    {"code",0 },
                    {"msg","上传成功" },
                    {"data",returnurl }
                };
                return dt;
            }
            catch (Exception ex)
            {
                //return new BaseResponse<string> { Success = false, Data = ex.Message, Code = 1 };
                Dictionary<string, object> dt = new Dictionary<string, object>()
                {
                    {"code",1},
                    {"msg",ex.Message }
                };
                return dt;
            }
        }


        /// <summary>
        /// 通过图片路径获取图片数据流
        /// </summary>
        /// <param name="PicturePath"></param>
        /// <returns></returns>
        [HttpGet]
        public object GetImgInfo(string PicturePath)
        {
            //将需要存储的图片读取为数据流
            FileStream fs = new FileStream(HostingEnvironment.MapPath("~/")+@PicturePath, FileMode.Open, FileAccess.Read);
            Byte[] btye2 = new byte[fs.Length];
            fs.Read(btye2, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            //将数据流读取为图片
            //System.IO.MemoryStream ms = new System.IO.MemoryStream(btye2);
            //System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            return btye2;
        }
    }
}
